package com.example.library.repository;

import com.example.library.model.Book;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.persistence.LockModeType;
import java.util.List;

public interface BookRepository extends JpaRepository<Book, Long> {
    @Query(value =
            "SELECT * FROM book " +
                    "WHERE LOWER(title) LIKE %:keyword% " +
                    "OR LOWER(author) LIKE %:keyword% " +
                    "OR isbn LIKE %:keyword%",
            nativeQuery = true)
    List<Book> findByKeyword(@Param("keyword") String keyword);

    @EntityGraph(attributePaths = {"borrowRecords"})
    @Override
    List<Book> findAll();

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT b FROM Book b WHERE b.id = :id")
    Book findByIdWithPessimisticLock(@Param("id") Long id);
}